<?php

namespace sffi\recovery;

use sffi\recovery\Driver\ArrayDriver;
use sffi\recovery\Driver\BaseDriver;
use sffi\recovery\Driver\IniDriver;
use sffi\recovery\Driver\JsonDriver;
use sffi\recovery\Driver\MysqlDriver;
use sffi\recovery\Driver\YamlDriver;
use RuntimeException;

/**
 * 工厂类
 * @method static ArrayDriver parseArray(array $array, array $config = [])
 * @method static JsonDriver parseJson(string $json, array $config = [])
 * @method static MysqlDriver parseMysql(string $path, array $config = [])
 * @method static YamlDriver parseYaml(string $path, array $config = [])
 * @method static IniDriver parseIni(string $path, array $config = [])
 */
class Factory
{
    protected static array $instances = [];

    /**
     * 静态回调方法
     * @param string $name 方法名称
     */
    public static function __callStatic(string $name,array $arguments)
    {
        $obj = self::getInstance(substr($name, 5));
        $obj->setConfig($arguments[1] ?? []);
        return $obj->parse(...$arguments);
    }

    /**
     * @return BaseDriver
     */
    public static function getInstance($name): BaseDriver
    {
        if (!isset(self::$instances[$name])) {
            $className = '\\sffi\\recovery\\Driver\\' . $name . 'Driver';
            if (class_exists($className)) {
                self::setInstance($name, new $className());
            } else {
                throw new RuntimeException('该方法不存在');
            }
        }
        return self::$instances[$name];
    }

    public static function setInstance($name, $instance): void
    {
        if ($instance instanceof BaseDriver) {
            self::$instances[$name] = $instance;
        }else {
            throw new \BadFunctionCallException('方法调用异常');
        }
    }
}